<template>
  <div v-if="open" class="play-mask">
    <div class="play-dialog">
      <div class="close-button" @click="handleClose">
        <img :src="closeIcon" />
      </div>
      <div id="meedu-player-container" class="play-box"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onBeforeUnmount, nextTick } from "vue";
import closeIcon from "@/assets/images/commen/close.png"

interface PropsInterface {
  id: number;
  url: string;
  open: boolean;
  onCancel: () => void;
}

const props = defineProps<PropsInterface>();

const open = ref(props.open);
const player = ref<any>(null);

watch(
  () => props.open,
  async (val) => {
    open.value = val;
    if (val && props.url) {
      // 等待 DOM 更新完成
      await nextTick();
      initDPlayer(props.url);
    }
  }
);

const handleClose = () => {
  destroyPlayer();
  props.onCancel();
};

const destroyPlayer = () => {
  if (player.value) {
    player.value.destroy();
    player.value = null;
  }
};

const initDPlayer = (playUrl: string) => {
  // 销毁现有的播放器
  destroyPlayer();
  
  // 确保容器存在
  const container = document.getElementById("meedu-player-container");
  if (!container) {
    console.error('Player container not found');
    return;
  }
  
  try {
    player.value = new window.DPlayer({
      container: container,
      autoplay: false,
      video: {
        url: playUrl,
      },
    });

    player.value.on("ended", () => {
      destroyPlayer();
      props.onCancel();
    });
  } catch (error) {
    console.error('DPlayer initialization failed:', error);
  }
};

// 组件卸载时销毁 player
onBeforeUnmount(() => {
  destroyPlayer();
});
</script>

<style scoped>
.play-mask {
  width: 100%;
  height: 100%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.45);
  z-index: 200;
}
.play-dialog {
  width: 800px;
  height: 450px;
  border-radius: 8px;
  position: relative;
}
.close-button {
  width: 30px;
  height: 30px;
  position: absolute;
  top: -30px;
  right: -30px;
  cursor: pointer;
  z-index: 1000;
}
.close-button:hover {
  opacity: 0.8;
}
.close-button img {
  width: 30px;
  height: 30px;
}
.play-box {
  width: 800px;
  height: 450px;
}
</style>